<template>
  <div class="menu-content">
    <!-- 搜索栏卡片 -->
    <el-card class="card-container search-card">
      <div class="search-container">
        <!-- 添加@input和@clear事件监听 -->
        <el-input v-model="searchParams.equipmentId" placeholder="请输入搜索的设备ID" class="search-input" clearable
          @input="handleSearch" @clear="handleSearch">
          <template #prefix>
            <el-icon class="el-input__icon">
              <Search />
            </el-icon>
          </template>
        </el-input>
        <!-- 添加搜索按钮 -->
        <el-button type="primary" @click="handleSearch" class="search-button">搜索</el-button>
      </div>
    </el-card>

    <!-- 表格卡片 -->
    <el-card class="card-container table-card">
      <el-table :data="maintenancePlans" stripe border class="custom-table rounded-table" v-loading="loading"
        style="width: 100%">
        <el-table-column prop="id" label="计划ID" align="center" min-width="80"></el-table-column>
        <el-table-column prop="content" label="维护任务" align="center" min-width="300"></el-table-column>
        <el-table-column prop="start" label="开始时间" align="center" min-width="140"></el-table-column>
        <el-table-column prop="end" label="结束时间" align="center" min-width="140"></el-table-column>
        <el-table-column prop="userId" label="创建人ID" align="center" min-width="100"></el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          layout="total, prev, pager, next, jumper" :prev-text="'上一页'" :next-text="'下一页'"
          @current-change="handleCurrentChange">
          <template #format-total="{ total }">
            总计 {{ total }} 条
          </template>
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';

export default {
  name: 'MaintenancePlan',
  components: { Search },
  setup() {
    // 状态管理
    const maintenancePlans = ref([]);
    const allMaintenancePlans = ref([]); // 新增：存储所有原始数据用于前端过滤
    const loading = ref(false);
    const searchParams = ref({ equipmentId: '' }); // 修改：重命名为equipmentId

    // 分页控制
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    // 格式化时间（支持字符串格式日期）
    // 格式化时间（直接显示时分秒）
    const formatTime = (timeStr) => {
      return timeStr || '无'; // 为空时显示"无"
    };

    // 获取维护计划数据
    const fetchMaintenancePlans = async () => {
      loading.value = true;
      try {
        const response = await request.get('/users/getMyMaintenanceSchedules');

        // 打印完整响应用于调试
        console.log('完整响应数据:', response);

        if (response && response.code === 200) {
          // 修复2：数据路径 - 直接使用response.data获取数据数组
          const formattedData = response.data || [];
          allMaintenancePlans.value = formattedData; // 存储原始数据
          total.value = formattedData.length;
          handleSearch(); // 触发搜索过滤

          // 调试信息
          console.log('处理后的数据:', formattedData);
          console.log('数据总数:', total.value);
        } else {
          // 显示后端返回的错误信息
          ElMessage.error(response?.msg || '获取维护计划失败: 未知错误');
        }
      } catch (error) {
        console.error('请求异常:', error);
        ElMessage.error('网络请求失败，请检查连接');
      } finally {
        loading.value = false;
      }
    };

    // 搜索处理
    const handleSearch = () => {
      currentPage.value = 1; // 重置页码
      let filtered = [...allMaintenancePlans.value];
      // 优化搜索逻辑，确保空值时显示所有数据
      if (searchParams.value.equipmentId && searchParams.value.equipmentId.trim()) {
        const equipmentId = searchParams.value.equipmentId.trim();
        // 仅对设备ID进行精确匹配搜索
        filtered = filtered.filter(plan =>
          plan.id && plan.id.toString() === equipmentId
        );
      }
      maintenancePlans.value = filtered;
      total.value = filtered.length;
    };

    // 分页变化处理
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fetchMaintenancePlans();
    };

    // 查看详情
    const viewDetails = (row) => {
      // 可以在这里实现查看详情的逻辑
      console.log('查看详情:', row);
      ElMessage.info('查看维护计划详情: ' + row.id);
    };

    // 标记已完成
    const handleComplete = async (row) => {
      try {
        // 从全局状态获取当前用户ID（请根据实际项目调整）
        const userId = localStorage.getItem('userId') || sessionStorage.getItem('userId');
        if (!userId) {
          ElMessage.error('用户信息缺失，请重新登录');
          return;
        }

        const response = await request.post('/api/user/completeRepair', {
          repairid: Number(row.id),
          status: 1,
          remark: '任务已完成',
          userid: Number(userId) // 确保为数字类型
        });

        if (response.code === 0) {
          ElMessage.success('标记成功');
          fetchMaintenancePlans(); // 刷新列表
        } else {
          ElMessage.error(response.msg || '操作失败');
        }
      } catch (error) {
        console.error('标记失败:', error);
        ElMessage.error('网络异常，请重试');
      }
    };

    // 初始化加载数据
    onMounted(() => {
      fetchMaintenancePlans();
    });

    return {
      searchParams,
      maintenancePlans,
      loading,
      currentPage,
      pageSize,
      total,
      handleSearch,
      handleCurrentChange,
      viewDetails
    };
  }
};
</script>

<style scoped>
/* 卡片容器样式 */
.card-container {
  width: 70%;
  margin: 0 auto 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-card {
  padding: 20px;
  margin-top: 20px;
}

.table-card {
  padding: 20px;
}

/* 搜索容器样式 */
.search-container {
  display: flex;
  gap: 10px;
  align-items: center;
  padding: 10px 0;
}

.search-input {
  flex: 1;
  /* 修改为flex布局让输入框自适应宽度 */
  max-width: none;
  /* 移除最大宽度限制 */
}

.search-button {
  min-width: 80px;
  /* 设置按钮最小宽度 */
}

/* 表格样式 */
::v-deep .custom-table {
  width: 100%;
  min-height: 400px;
}

::v-deep .rounded-table {
  border-radius: 12px !important;
  overflow: hidden !important;
  border: none !important;
}

/* 表头样式 */
::v-deep .custom-table .el-table__header-wrapper th {
  background-color: #1890ff !important;
  color: white !important;
  font-weight: 500;
  border-bottom: 2px solid white !important;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: center;
  position: static;
  bottom: auto;
  left: auto;
  transform: none;
  background-color: transparent;
  padding: 0;
  box-shadow: none;
}

/* 表格行悬浮效果 - 修改为与RobotLogs.vue一致 */
/* 移除原有的表格行悬浮样式 */
/* ::v-deep .el-table .el-table__row { ... } */
/* ::v-deep .el-table .el-table__row:hover { ... } */
/* ::v-deep .custom-table .el-table__body .el-table__row:hover { ... } */
/* ::v-deep .el-table__body tr.el-table__row:hover>td { ... } */

/* 添加与UserQuery.vue完全一致的表格悬浮样式 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row {
  transition: all 0.2s ease;
  position: relative;
}

/* 优化悬浮效果，防止内容溢出 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row:hover {
  transform: scale(1.01);
  transform-origin: center left;
  color: #fff !important;
  font-size: 15px;
  z-index: 10;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 0 5px;
}

/* 三级选择器设置单元格背景色 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row:hover td {
  background-color: #1890ff !important;
  color: #fff !important;
}

/* 确保表格有足够宽度容纳放大后的内容 */
::v-deep .el-table__body {
  width: 100% !important;
}

/* 操作按钮样式保持不变 */
::v-deep .el-table .el-button--text {
  color: #1890ff;
}

::v-deep .el-table .el-table__row:hover .el-button--text {
  color: white !important;
}
</style>